class ProjectsController < ApplicationController
  before_filter :login_required

  helper [:Projects,:Issues]

  require_role ["admin","pdm"], :only => [:edit, :change_state]

  in_place_edit_for :project, :priority

  def index
    #@projects = Project.all(:conditions => ["state != ?", "freeze"], :order => 'priority DESC, should_be_finish_time ASC')
  end

  def new
    @project = Project.new

    respond_to do |format|
      format.html
    end
  end

  def show
    @project = Project.find(params[:id])
    
    sort = case params['sort']
    when "issueid"          then "issueid"
    when "priority"         then "priority"
    when "created_at"       then "created_at"
    when "state"            then "state"
    when "issueid_reverse"  then "issueid DESC"
    when "priority_reverse" then "priority DESC"
    when "created_reverse"  then "created_at DESC"
    when "state_reverse"    then "state DESC"
    end

    unless params[:issue_type] == nil
      @issues = @project.issues.get_issues(params[:issue_type], sort)
    else
      @issues = @project.issues.all(:order => sort)
    end

    if request.xml_http_request?
      render :partial => "issues_list", :layout => false
    else
      render :layout => "list"
    end

  end

  def create
    @project = Project.new(params[:project])

    respond_to do |format|
      if @project.save
        flash[:notice] = 'Project was successfully created.'
        format.html { redirect_to :controller => :projects, :action => :all }
      else
        format.html { render :action => "new" }
      end
    end
  end

  def all
    @projects = Project.paginate :page => params[:page], :order => 'created_at DESC', :per_page => 20
    #render :layout => "list"
  end

  def change_state
    @project = Project.find(params[:id])

    @project_previous_state = @project.state

    if @project.state == "released" || @project.state == "need_to_release"
      @project.working
    else
      @project.rework
    end

    @project_current_state = @project.state
    
    redirect_to :back
  end

  def list
    items_per_page = 10

    sort = case params['sort']
    when "name"  then "name"
    when "qty"   then "quantity"
    when "price" then "price"
    when "name_reverse"  then "name DESC"
    when "qty_reverse"   then "quantity DESC"
    when "price_reverse" then "price DESC"
    end

    conditions = ["name LIKE ?", "%#{params[:query]}%"] unless params[:query].nil?

    @total = Item.count(:conditions => conditions)
    @items_pages, @items = paginate :items, :order => sort, :conditions => conditions, :per_page => items_per_page

    if request.xml_http_request?
      render :partial => "issues_list", :layout => false
    end
  end

  def export_csv
    @project = Project.find(params[:id])
    @issues = @project.issues
    require 'fastercsv'
    csv_string = FasterCSV.generate(:col_sep => "\t", :row_sep => "\r\n") do |csv|
      csv << ['ID', '优先级', 'P1','P2','R','S','步骤','标题','描述','比率','测试卡类型','测试样机','状态','开发人员']
      @issues.each do |i|
        developer_name = ""
        developer_name = i.developer[0].name unless i.developer.empty?
        csv << [i.project.key + "-IS-" + i.issueid.to_s,
                i.priority,
                i.P1,
                i.P2,
                i.R,
                i.S,
                i.step,
                i.title,
                i.description,
                i.ratio,
                i.card_type,
                i.phoneid,
                trans_issue_state_to_chs(i.state),
                developer_name
              ]
      end
    end
    send_data("FFFE".gsub(/\s/,'').to_a.pack("H*") + encode_convert(csv_string, "UTF-16LE", "UTF-8"), :type => 'text/csv; charset=utf16; header=present', :filename => "#{@project.name + "'s_Buglists"}.csv")
  end

  def edit
    @project = Project.find(params[:id])
  end

  def update
    @project = Project.find(params[:id])

    respond_to do |format|
      if @project.update_attributes(params[:project])
        flash[:notice] = 'Project\'s information was successfully updated.'
        format.html { redirect_to project_path }
      else
        format.html { render :action => "edit" }
      end
    end
    
  end

  private

  def encode_convert(s, to, from)
    require 'iconv'
    begin
      converter = Iconv.new(to, from)
      converter.iconv(s)
    rescue
      s
    end
  end

  def trans_current_state_to_chs(string)
    case string
    when "need_to_release"
      "未量产"
    when "released"
      "已量产"
    when "freeze"
      "冻结"
    end
  end

  def trans_issue_state_to_chs(string)
    case string
    when "submitted"
      "未分配"
    when "assigned"
      "打开"
    when "resolved"
      "待测试"
    when "finished"
      "已关闭"
    when "reopen"
      "重新开启"
    when "suspend"
      "挂起"
    end
  end

end
